package org.apache.doris.demo.spring.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mysql.cj.util.StringUtils;
import org.apache.doris.demo.spring.model.User;
import org.apache.doris.demo.spring.model.UserTag;
import org.apache.doris.demo.spring.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@Controller
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping
    public String listUsers(Model model) {
        model.addAttribute("users", userService.list());
        return "user/index";
    }

    @GetMapping("/add")
    public String addUserForm(Model model) {
        User user = new User();
        user.setRegisterTime(LocalDateTime.now());
        model.addAttribute("user", user);

        return "user/form";
    }

    @PostMapping("/add")
    public String addUser(User user) {
        userService.save(user);
        return "redirect:/users";
    }

    @GetMapping("/edit/{id}")
    public String editUserForm(@PathVariable("id") Long id, Model model) {
        model.addAttribute("user", userService.getById(id));
        return "user/form";
    }

    @PostMapping("/edit/{id}")
    public String editUser(@PathVariable("id") Long id, User user) {
        userService.updateById(user);
        return "redirect:/users";
    }

    @GetMapping("/delete/{id}")
    public String deleteUser(@PathVariable("id") Long id) {
        userService.removeById(id);
        return "redirect:/users";
    }


    @ResponseBody
    @GetMapping("/search/{userid}")
    public List<User> searchTags(@PathVariable ("userid") String userid) {
        QueryWrapper<User> userTagQueryWrapper = new QueryWrapper<>();
        userTagQueryWrapper.like("username",userid);
        try{
            long phone = Long.parseLong(userid);
            userTagQueryWrapper.or().like("phone",phone).or().like("user_id",phone);
        }catch(NumberFormatException e){

        }
        return userService.list(userTagQueryWrapper);
    }
    @ResponseBody
    @GetMapping("/search/")
    public List<User> searchAllTags() {
        return userService.list(null);
    }
}